package yxy.game.pm2.command.hero;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.gacha.GachaHeroHandle;
import yxy.game.pm2.module.gacha.GachaHeroModule;
import yxy.game.pm2.module.gacha.GachaHeroType;
import yxy.game.pm2.module.hero.HeroHandle;


@MessageType(proto = Command.GachaHero, classtype = HeroMessage.GachaHeroRequest.class)
public class CMD_GachaHero extends Command<HeroMessage.GachaHeroRequest> {

    @Override
    public void execute(MessageSource messageSource, HeroMessage.GachaHeroRequest request) {


        String playerCode = messageSource.getTag();
        int type = request.getType();
        int times = request.getTimes();

        HeroMessage.GachaHeroResponse.Builder response = HeroMessage.GachaHeroResponse.newBuilder();

        GachaHeroType gachaType = GachaHeroType.forNumber(type);
        if (gachaType == null) {
            send(messageSource, response, Result.ParamError);
            return;
        }

        switch (times) {
            case 1:
                break;
            case 10:
                break;
            default:
                send(messageSource, response, Result.ParamError);
                return;
        }


        HeroHandle herosModule = new HeroHandle();
        int upper = herosModule.getUpper(playerCode);
        if (herosModule.getHerosSize(playerCode) + times > upper) {
            // 武将数超上限
            send(messageSource, response, Result.HeroCountUpper);// 武将背包空余位置不足
            return;
        }


        GachaHeroModule module = GachaHeroModule.get(playerCode);
        try {
            if (module.tryLock()) {
                Result result = new GachaHeroHandle().summonHero(module, gachaType, times, response);
                response.setType(type);
                send(messageSource, response, result);
            }


        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        } finally {
            module.unlock();
        }


    }

    private void send(MessageSource messageSource, HeroMessage.GachaHeroResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }

}
